// 缓存管理模块
export interface CacheEntry {
  id: string
  path: string
  scanMode: string
  detectionMode: string
  similarityThreshold: number
  minFileSize: number
  maxFileSize: number
  totalFiles: number
  duplicateGroups: number
  duplicateFiles: number
  savedSpace: string
  groups: any[]
  timestamp: number
  fileCount: number
  totalSize: string
}

export interface CacheConfig {
  maxEntries: number
  maxAge: number // 毫秒
  storageKey: string
}

class CacheManager {
  private config: CacheConfig
  private cache: Map<string, CacheEntry>

  constructor(config: Partial<CacheConfig> = {}) {
    this.config = {
      maxEntries: 50,
      maxAge: 24 * 60 * 60 * 1000, // 24小时
      storageKey: 'file-deduplicator-cache',
      ...config
    }
    this.cache = new Map()
    this.loadFromStorage()
  }

  // 生成缓存键
  private generateKey(path: string, scanMode: string, detectionMode: string, similarityThreshold: number, minFileSize: number, maxFileSize: number): string {
    const keyData = `${path}|${scanMode}|${detectionMode}|${similarityThreshold}|${minFileSize}|${maxFileSize}`
    // 使用encodeURIComponent处理非Latin1字符，然后转换为base64
    try {
      return btoa(encodeURIComponent(keyData)).replace(/[^a-zA-Z0-9]/g, '')
    } catch (error) {
      // 如果仍然失败，使用简单的哈希算法
      return this.simpleHash(keyData)
    }
  }

  // 简单的哈希算法作为备选方案
  private simpleHash(str: string): string {
    let hash = 0
    if (str.length === 0) return hash.toString()
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash // 转换为32位整数
    }
    return Math.abs(hash).toString(36)
  }

  // 检查缓存是否有效
  private isValid(entry: CacheEntry): boolean {
    const now = Date.now()
    return (now - entry.timestamp) < this.config.maxAge
  }

  // 从localStorage加载缓存
  private loadFromStorage(): void {
    try {
      const stored = localStorage.getItem(this.config.storageKey)
      if (stored) {
        const data = JSON.parse(stored)
        this.cache = new Map(Object.entries(data))
        
        // 清理过期缓存
        this.cleanup()
      }
    } catch (error) {
      console.warn('加载缓存失败:', error)
      this.cache = new Map()
    }
  }

  // 保存缓存到localStorage
  private saveToStorage(): void {
    try {
      const data = Object.fromEntries(this.cache)
      localStorage.setItem(this.config.storageKey, JSON.stringify(data))
    } catch (error) {
      console.warn('保存缓存失败:', error)
    }
  }

  // 清理过期和超量的缓存
  private cleanup(): void {
    const now = Date.now()
    const validEntries = Array.from(this.cache.entries())
      .filter(([_, entry]) => this.isValid(entry))
      .sort(([_, a], [__, b]) => b.timestamp - a.timestamp)

    // 限制缓存条目数量
    if (validEntries.length > this.config.maxEntries) {
      validEntries.splice(this.config.maxEntries)
    }

    this.cache = new Map(validEntries)
    this.saveToStorage()
  }

  // 获取缓存
  get(path: string, scanMode: string, detectionMode: string, similarityThreshold: number, minFileSize: number, maxFileSize: number): CacheEntry | null {
    const key = this.generateKey(path, scanMode, detectionMode, similarityThreshold, minFileSize, maxFileSize)
    const entry = this.cache.get(key)
    
    if (entry && this.isValid(entry)) {
      console.log('缓存命中:', path)
      return entry
    }
    
    if (entry) {
      console.log('缓存已过期:', path)
      this.cache.delete(key)
    }
    
    return null
  }

  // 设置缓存
  set(entry: Omit<CacheEntry, 'id' | 'timestamp'>): void {
    const key = this.generateKey(entry.path, entry.scanMode, entry.detectionMode, entry.similarityThreshold, entry.minFileSize, entry.maxFileSize)
    
    const cacheEntry: CacheEntry = {
      ...entry,
      id: key,
      timestamp: Date.now()
    }
    
    this.cache.set(key, cacheEntry)
    console.log('缓存已保存:', entry.path)
    
    // 保存到localStorage
    this.saveToStorage()
    
    // 清理过期缓存
    this.cleanup()
  }

  // 删除特定缓存
  delete(path: string, scanMode: string, detectionMode: string, similarityThreshold: number, minFileSize: number, maxFileSize: number): boolean {
    const key = this.generateKey(path, scanMode, detectionMode, similarityThreshold, minFileSize, maxFileSize)
    const deleted = this.cache.delete(key)
    if (deleted) {
      this.saveToStorage()
    }
    return deleted
  }

  // 清空所有缓存
  clear(): void {
    this.cache.clear()
    localStorage.removeItem(this.config.storageKey)
    console.log('所有缓存已清空')
  }

  // 获取缓存统计信息
  getStats(): { total: number; valid: number; expired: number } {
    const now = Date.now()
    let valid = 0
    let expired = 0
    
    for (const entry of this.cache.values()) {
      if (this.isValid(entry)) {
        valid++
      } else {
        expired++
      }
    }
    
    return {
      total: this.cache.size,
      valid,
      expired
    }
  }

  // 获取缓存列表
  getEntries(): CacheEntry[] {
    return Array.from(this.cache.values())
      .sort((a, b) => b.timestamp - a.timestamp)
  }
}

// 导出单例实例
export const cacheManager = new CacheManager()

// 导出工具函数
export const createCacheEntry = (data: Omit<CacheEntry, 'id' | 'timestamp'>): Omit<CacheEntry, 'id' | 'timestamp'> => data
